package com.example.xlmkotlinwanandroid.ext

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

//对retrofit2的返回值增加一个拓展函数进行回调
//定义的拓展函数需要返回值为T，保证线程能切回来
//内部使用resume和resumewithexception将正确和错误的数据回调

suspend fun <T> Call<T>.await():T {
    return suspendCoroutine { continuation ->
        enqueue(object : Callback<T> {

            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                if (body != null) continuation.resume(body)
                else continuation.resumeWithException(RuntimeException("response body is null"))


            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }


        })

    }
}